package com.ushine.web.communication.websocket.config;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: yls
 * @Date: 2021/1/22 10:33
 * @Description: 实现消息监听
 * @Version 1.0
 */
@Slf4j
@Component
@SuppressWarnings("unchecked")
public class MessageHandler extends TextWebSocketHandler {
    private static final String MODEL = "webSocket通信=》";

    private List<WebSocketSession> clients = new ArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        clients.add(session);
        log.info("{}uri：{}", MODEL, session.getUri());
        log.info("{}连接建立：{}", MODEL, session.getId());
        log.info("{}current session：{}", MODEL, clients.size());
    }

    /**
     * 功能描述:
     * 〈断开连接后〉
     *
     * @param session session
     * @param status  状态
     * @return : void
     * @author : yls
     * @date : 2021/1/22 10:38
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        clients.remove(session);
        log.info("{}断开连接：{}", MODEL, session.getId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        Map<String, String> map = JSONObject.parseObject(payload, HashMap.class);
        log.info("{}接收到的数据：{}", MODEL, map);
        clients.forEach(client -> {
            log.info("{}发送消息给：{}", MODEL, session.getId());
            try {
                client.sendMessage(new TextMessage(MODEL + "服务器返回收到的信息：" + payload));
            } catch (IOException e) {
                log.error("{}发送消息失败，", MODEL, e);
            }
        });
    }
}
